
import base64
import json
import cv2
import os
import numpy as np
#from common.utils import *

#/************************************************************************************************************************
#**************************************base64图像并用http传输方式出入参说明*************************************************
#************************************************************************************************************************/

def base642im(img_str):
    # 此时可以测试解码得到图像并显示，服务器端也按照下面的方法还原图像继续进一步处理
    img_decode_ = img_str.encode('ascii')  # ascii编码
    img_decode = base64.b64decode(img_decode_)  # base64解码
    img_np = np.frombuffer(img_decode, np.uint8)  # 从byte数据读取为np.array形式
    img = cv2.imdecode(img_np, cv2.COLOR_RGB2BGR)  # 转为OpenCV形式
    #img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    #img = Image.fromarray(img, mode='RGB')  # 根据网络的输入
    #imshow('adf', img, -1)
    return img

def numpy2base64(image):
    # 将NumPy数组转换为图像
    img_encode = cv2.imencode('.jpg', image)[1]
    img_bytes = img_encode.tobytes()

    # 进行Base64编码
    img_str = base64.b64encode(img_bytes).decode('ascii')

    return img_str

def in_add_image(data, id, np_img):
    base64_image1_buffer = numpy2base64(np_img)
    aa = {"id": id, "data": base64_image1_buffer}
    data['camera_data']['images'].append(aa)
    return data

def in_get_images(data):
    imgs = []
    name = data['camera_data']['name']
    for x in data['camera_data']['images']:
        img = base642im(x['data'])
        imgs.append([x['id'], img])
    return name, imgs

def in_add_standard_youwu(data):
    aa = {
        "label": "shangbiao", # 
        "type": "YOUWU",      # NUM（数量）, OCR, DEFECT(缺陷), YOUWU(检测有无，有-YOU,无-WU)
        "standard": "YOU",
        "template": {        # 使用模板匹配时，此处会给出模板的信息
            "name": "d:\\template_data/template1.jpg",
            "coordinate": {
                "type": "RECTANGLE",
                "list_point": [
                    [
                        440,
                        520
                    ],
                    [
                        1980,
                        520
                    ],
                    [
                        1980,
                        1430
                    ],
                    [
                        440,
                        1430
                    ]
                ],
                "center": [
                    100,
                    200
                ],
                "radius": 300
            }
        }
    }
    data['camera_data']['standards'].append(aa)
    return data

def in_add_standard_num(data):
    aa = {
        "label": "jiaofa", 
        "type": "NUM", # NUM（数量）, OCR, DEFECT(缺陷)
        "standard": 2,
        "template": {}
    }
    data['camera_data']['standards'].append(aa)
    return data

def in_add_standard_ocr(data):
    aa = {
        "label": "biaotie", # 
        "type": "OCR", # NUM（数量）, OCR, DEFECT(缺陷)
        "standard": "MIDEA_MODEL1234"
    }
    data['camera_data']['standards'].append(aa)
    return data

def in_add_standard_quexian(data):
    aa = {
        "label": "quexian",
        "type": "DEFECT" # NUM（数量）, OCR, DEFECT(缺陷)
    }
    data['camera_data']['standards'].append(aa)
    return data

# 按相机（检测面）送检，一个相机送一次算法（包含多张图、此相机的检测项标准等信息）
def get_in_args(name="相机1"):
    return { 
        "barcode": "511230J60191B230120001", # 可空
        "mes_info": {                        # 所获取MES信息，可空
            "MODEL_NAME": "KFR-35G/M1-1",
            "CUSTOMER_MODEL": "KFR-35G/M1-1", #外销标准
            "CONSUME_COUNTRY": "国内",
            "MITEM_CODE": "21022011009480", #内销标准
        },
        "camera_data": {
            "name": name,
            "images": [
                #{"id": "s123412", "data": "base64_image1_buffer"},
                #{"id": "s123413", "data": "base64_image2_buffer"}
            ],
            "standards": [ # 此面相机所需检测物，检测项标准,
            ]
        }
    }


#/************************************** 出参 ,算法根据客户端送的检测图像和检测标准，给检测结果************************************************/

def out_set_total_result(data, end):
    data['data']['result']['total_result'] = 'NG' if end else 'OK'
    return data

def out_add_standard_result_youwu(data):
    aa = {
        "label" : "shangbiao",  #
        "type": "YOUWU", # NUM（数量）, OCR, DEFECT(缺陷), YOUWU(检测有无，有-YOU,无-WU)
        "standard" : "YOU", #入参传入
        "algo_result": "WU", # 算法返回内容，如果用错了，检测结果为wu
        "detect_result": "NG" #单个检测项的判断结果，如果贴错了，返回NG
    }
    data['data']['result']['standard_result'].append(aa)
    return data

def out_add_standard_result_num(data):
    aa = {
        "label": "jiaofa", # 算法返回内容
        "type": "NUM", # NUM（数量）, OCR, DEFECT(缺陷)、
        "standard" : "2",
        "algo_result": 1, # 算法返回数量
        "detect_result" : "NG" 
    }
    data['data']['result']['standard_result'].append(aa)
    return data

def out_add_standard_result_string(data):
    aa = {
        "label": "biaotie", # 算法返回内容
        "type": "STRING", # NUM（数量）, STRING, DEFECT(缺陷)
        "standard" : "MIDEA_MODEL1234", 
        "algo_result": "MIDEA_MODEL123", # 算法返回内容
        "detect_result" : "NG" 
    }
    data['data']['result']['standard_result'].append(aa)
    return data

def out_add_standard_result_quexian(data):
    aa = {
        "label": "quexian", 
        "type": "DEFECT", # NUM（数量）, OCR, DEFECT(缺陷)
        "detect_result":"NG"
    }
    data['data']['result']['standard_result'].append(aa)
    return data

def out_get_images_rect(rect, label, score):
    x1, y1, x2, y2 = rect[:4]
    list_point = [[x1, y1], [x2, y1], [x2, y2], [x1, y2]]
    center = np.mean(list_point, axis=0).tolist()
    radius = (abs(x2-x1)+abs(y2-y1))/4
    aa = {
        "label": label, #展示标签
        "scores": float(score/100), #分数
        "type": "RECTANGLE", #坐标类型 RECTANGLE-矩形, POLYGON-多边形, ROUND圆形，中心和半径
        "list_point": list_point,
        "center": center, # 当以圆形框选时，坐标；圆心
        "radius": radius #半径
    }
    return aa

def out_add_images_bnds(data, imgid, bnds, end, ends, save_img):
    bb = {
        "id": imgid, # 图像id，用于区分图像，用以判断存/展示哪张有效图像
        "coordinate": [# coordinate
        ]
    }
    for x in bnds:
        rect, label, score = x[:3]
        aa = out_get_images_rect(rect, label, score)
        bb['coordinate'].append(aa)

    bb['end'] = end
    bb['ends'] = ends
    bb['save_img'] = save_img
    data['data']['result']['images'].append(bb)
    return data

def get_out_args():
    return {
        "code": "00000", # 业务代码，正常为00000，异常代码自定义
        "success": True,
        "msg": "算法调用成功",
        "data": {
            "result": {
                "total_result": "OK", # OK,NG, 经standard_result 分析后的相机维度的总结果
                "camera_name": "相机1",
                "standard_result":[  # 检测项标准和检测项的结果
                ],
                "images": [ # 要存图的图像信息
                ]
            }
        }
    }


#/************************************************************************************************************************
#**************************************图像采用共享内存方式，并用http传输参数，出入参说明*************************************
#************************************************************************************************************************/
# 入参
def get_in_args_memshare():
    return {
        "barcode": "511230J60191B230120001", # 可空
        "mes_info": {
            "MODEL_NAME": "KFR-35G/M1-1",
            "CUSTOMER_MODEL": "KFR-35G/M1-1", #外销标准
            "CONSUME_COUNTRY": "国内",
            "MITEM_CODE": "21022011009480", #内销标准
        },
        "camera_data": {
            "name": "相机1",
            "images": [
                {
                    "id": "S13213214", # 图像id，用于区分图像
                    "name": "cam1_image1", # 图片buffer共享内存地址
                    "size": 102400 # 共享内存的图像大小
                }
            ],
            "standards": [ # 检测项标准
                {
                    "label": "shangbiao", # 
                    "type": "YOUWU", # NUM（数量）, OCR, DEFECT(缺陷), YOUWU(检测有无，有-YOU,无-WU)
                    "standard": "YOU",
                    "template": {
                        "name": "d:\\aidata/template1.jpg",
                        "coordinate": {
                            "type": "RECTANGLE",
                            "list_point": [
                                [
                                    440,
                                    520
                                ],
                                [
                                    1980,
                                    520
                                ],
                                [
                                    1980,
                                    1430
                                ],
                                [
                                    440,
                                    1430
                                ]
                            ],
                            "center": [
                                100,
                                200
                            ],
                            "radius": 300
                        }
                    }
                },
                {
                    "label": "jiaofa", # 
                    "type": "NUM", # NUM（数量）, OCR, DEFECT(缺陷)
                    "standard": 2,
                    "template": {
                        "name": "d:\\aidata/template1.jpg",
                        "coordinate": {
                            "type": "RECTANGLE",
                            "list_point": [
                                [
                                    440,
                                    520
                                ],
                                [
                                    1980,
                                    520
                                ],
                                [
                                    1980,
                                    1430
                                ],
                                [
                                    440,
                                    1430
                                ]
                            ],
                            "center": [
                                100,
                                200
                            ],
                            "radius": 300
                        }
                    }
                },
                {
                    "label": "biaotie", # 
                    "type": "OCR", # NUM（数量）, OCR, DEFECT(缺陷)
                    "standard": "MIDEA_MODEL1234"
                },
                {
                    "label": "quexian",
                    "type": "DEFECT" # NUM（数量）, OCR, DEFECT(缺陷)
                }
            ]
        }
    }
#/************************************** 出参 ************************************************/
def get_out_args_memshare():
    {
        "code": "00000", # 业务代码，正常为00000，异常代码自定义
        "success": True,
        "msg": "算法调用成功",
        "data": {
            "result": {
                "total_result": "OK", # OK,NG, 经standard_result 分析后的相机维度的总结果
                "camera_name": "相机1",
                "standard_result":[
                    {
                        "label" : "shangbiao",  #
                        "type": "YOUWU", # NUM（数量）, OCR, DEFECT(缺陷), YOUWU(检测有无，有-YOU,无-WU)
                        "standard" : "YOU", #入参传入
                        "algo_result": "WU", # 算法返回内容，如果用错了，检测结果为wu
                        "detect_result": "NG" #单个检测项的判断结果，如果贴错了，返回NG
                    },
                    {
                        "label": "jiaofa", # 算法返回内容
                        "type": "NUM", # NUM（数量）, OCR, DEFECT(缺陷)、
                        "standard" : "2",
                        "algo_result": 1, # 算法返回数量
                        "detect_result" : "NG" 
                    },
                    {
                        "label": "biaotie", # 算法返回内容
                        "type": "OCR", # NUM（数量）,OCR, DEFECT(缺陷)
                        "standard" : "MIDEA_MODEL1234", 
                        "algo_result": "MIDEA_MODEL123", # 算法返回内容
                        "detect_result" : "NG" 

                    },
                    {
                        "label": "quexian", 
                        "type": "DEFECT", # NUM（数量）, OCR, DEFECT(缺陷)
                        "detect_result":"NG"
                    }
                ],
                "images": [ # 要存图的图像信息
                    {   
                        "id": "S13213214", # 图像id，用于区分图像
                        "name": "cam1_image1", # 图片buffer共享内存地址
                        "size": 102400, # 共享内存的图像大小
                        "coordinate": [
                            {
                                "label": "sfa", #展示标签
                                "scores": 0.8341, #分数
                                "type": "RECTANGLE", # RECTANGLE-矩形, POLYGON-多边形, ROUND圆形，中心和半径
                                "list_point": [ # 顺时针点集
                                    [
                                        123,
                                        456
                                    ], # 点坐标x,y，矩形左上角
                                    [
                                        123,
                                        456
                                    ], # 点坐标x,y，矩形右上角
                                    [
                                        123,
                                        456
                                    ], # 点坐标x,y，矩形右下角
                                    [
                                        123,
                                        456
                                    ] # 点坐标x,y，矩形左下角
                                ],
                                "center": [
                                    100,
                                    200
                                ], # 当以圆形框选时，坐标；圆心
                                "radius": 300 #半径
                            }
                        ]
                    }
                ]
            }
        }
    }



